package org.xxpay.manage.channelmch.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.entity.*;
import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.RpcCommonService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author: liam
 * @date: 18/05/06
 * @description: 渠道商通道配置
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/channelmch_passage")
public class ChannelMchPassageController extends BaseController {

    @Autowired
    private RpcCommonService rpcCommonService;
    /*
   *添加渠道商拥有通道
   * */
    @RequestMapping("/add")
    @ResponseBody
    public ResponseEntity<?> add(HttpServletRequest request, ChannelMchChannelInfo channelMchChannelInfo) {
        try {
            BigDecimal bi2 = new BigDecimal(100);
            BigDecimal divide = channelMchChannelInfo.getChannelMchRate().divide(bi2, 6, RoundingMode.HALF_UP);
            channelMchChannelInfo.setChannelMchRate(divide);
            channelMchChannelInfo.setCreateTime(new Date());
            channelMchChannelInfo.setUpdateTime(new Date());
            int res = rpcCommonService.rpcChannelMchChannelInfoService.add(channelMchChannelInfo);
            if (res != 1) ResponseEntity.ok(XxPayResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseEntity.ok(BizResponse.buildSuccess());
    }


    /*
    * 获取支付通道
    * */
    @RequestMapping("/getPayPassageList")
    @ResponseBody
    public ResponseEntity<?> getPayPassageList(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        //获取支付类型，
        String payType = getStringRequired(param, "payType");
        //获取渠道商ID信息
        Long channelMchId = getLongRequired(param, "channelMchId");
        System.out.println(payType+"---"+channelMchId);
        ChannelMchInfo channelAgentMchInfo = rpcCommonService.rpcChannelMchInfoService.findBychannelMchId(channelMchId);
        //如果没有上级渠道代理商的情况下，返回的支付通道
        long supChannelMchAgentId=channelAgentMchInfo.getSupChannelMchAgentId();
        if(supChannelMchAgentId==0){
            List<PayPassage> payPassageList = rpcCommonService.rpcPayPassageService.selectAllByPayType(payType);
            return ResponseEntity.ok(XxPayResponse.buildSuccess(payPassageList));
        }else{
            List<JSONObject> objects = new LinkedList<>();
            //获取上级拥有的支付产品
            List<ChannelAgentMchChannelInfo> channelAgentMchChannelInfoLists = rpcCommonService.rpcChannelAgentMchChannelInfoService.selectByChannelAgentMchId(supChannelMchAgentId);
            for (ChannelAgentMchChannelInfo channelAgentMchChannelInfo:channelAgentMchChannelInfoLists) {
               // JSONObject object = (JSONObject) JSON.toJSON(channelAgentMchChannelInfo);
                JSONObject object = new JSONObject();
                //如果信息表中有匹配paytype的则查出来显示
                if (channelAgentMchChannelInfo.getPayproduct()==Integer.valueOf(payType)) {
                    PayPassage payPassage = rpcCommonService.rpcPayPassageService.findById(channelAgentMchChannelInfo.getPaypassage());
                    object.put( "passageName",payPassage.getPassageName());
                    object.put( "id",payPassage.getId());
                    objects.add(object);
                }
            }
            return ResponseEntity.ok(XxPayResponse.buildSuccess(objects));
        }
    }

    /**
     * 查询渠道商信息是否有上级，如果没有上级则查询所有支付产品
     * 有上级只给他上级所拥有的产品
     * @return
     */
    @RequestMapping("/getPayProductList")
    @ResponseBody
    public ResponseEntity<?> getPayProductList(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long channelMchId = getLongRequired(param, "channelMchId");
        ChannelMchInfo channelAgentMchInfo = rpcCommonService.rpcChannelMchInfoService.findBychannelMchId(channelMchId);
        long supChannelMchAgentId=channelAgentMchInfo.getSupChannelMchAgentId();
        if(supChannelMchAgentId==0){
            //代表他没有上级，查询当前可用开启支付产品
            PayProduct queryPayProduct = new PayProduct();
            queryPayProduct.setStatus(MchConstant.PUB_YES);
            List<PayProduct> payProductList = rpcCommonService.rpcPayProductService.selectAll(queryPayProduct);
            return ResponseEntity.ok(XxPayResponse.buildSuccess(payProductList));
        }else{
            //查询他上级所拥有的产品
            //先获取他的上级渠道商是谁（supChannelMchAgentId），在查询他上级拥有的通道，以及各通道的费率
            List<JSONObject> objects = new LinkedList<>();
            List<ChannelAgentMchChannelInfo> channelAgentMchChannelInfoLists = rpcCommonService.rpcChannelAgentMchChannelInfoService.selectByChannelAgentMchId(supChannelMchAgentId);
            for (ChannelAgentMchChannelInfo channelAgentMchChannelInfo:channelAgentMchChannelInfoLists) {
                JSONObject object = (JSONObject) JSON.toJSON(channelAgentMchChannelInfo);
                //这里的payproduct和t_pay_product中的paytype字段是关联的
                int paytype = channelAgentMchChannelInfo.getPayproduct();
                //根据paytype查询t_pay_product表中的支付产品信息
                PayProduct payProduct = new PayProduct();
                payProduct.setPayType(String.valueOf(paytype));
                List<PayProduct> payProductlist = rpcCommonService.rpcPayProductService.selectAll(payProduct);
                for (PayProduct p:payProductlist) {
                    object.put( "productName",p.getProductName());
                    object.put( "payProductId",p.getId());
                    object.put( "payType",p.getPayType());
                    object.put( "supChannelMchAgentId",supChannelMchAgentId);
                }
                //一个渠道代理商下拥有同一个支付产品，但是支付产品下可能会有不同的支付通道，所以也查出来显示一下方便区分
                PayPassage payPassage= rpcCommonService.rpcPayPassageService.findById(channelAgentMchChannelInfo.getPaypassage());
                object.put( "passageName",payPassage.getPassageName());
                objects.add(object);
            }

            return ResponseEntity.ok(XxPayPageRes.buildSuccess(objects));
        }
    }
    /**
     * 查询某个通道下的上级代理通道费率
     * @return
     */
    @RequestMapping("/getChannelSupRate")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request, ChannelAgentMchChannelInfo channelAgentMchChannelInfo) {
        JSONObject param = getJsonParam(request);
        ChannelAgentMchChannelInfo channelAgentMchChannelInfo1 =  rpcCommonService.rpcChannelAgentMchChannelInfoService.find(channelAgentMchChannelInfo);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(channelAgentMchChannelInfo1));
    }

    /*
   * payduct参数实为pay_product中的paytype
   * 查询出所有渠道商拥有的通道信息
   * */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        ChannelMchChannelInfo channelMchChannelInfo = getObject(param, ChannelMchChannelInfo.class);
        int count = rpcCommonService.rpcChannelMchChannelInfoService.count(channelMchChannelInfo);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<ChannelMchChannelInfo> channelMchChannelInfos = rpcCommonService.rpcChannelMchChannelInfoService.select((getPageIndex(param) - 1) * getPageSize(param), getPageSize(param), channelMchChannelInfo);
        List<JSONObject> objects = new LinkedList<>();
        for(ChannelMchChannelInfo info : channelMchChannelInfos) {
            JSONObject object = (JSONObject) JSON.toJSON(info);
            //获取支付通道id，对应t_pay_passage中id
            int id= Integer.valueOf(info.getPaypassage());
            System.out.println("id------"+id);
            // 获取支付类型中paytype，对应t_pay_product中paytype
            int paytype = info.getPayproduct();
            PayPassage payPassage= rpcCommonService.rpcPayPassageService.findById(id);
            object.put( "passageName",payPassage.getPassageName());
            PayProduct payProduct = new PayProduct();
            payProduct.setPayType(String.valueOf(paytype));
            List<PayProduct> payProductlist = rpcCommonService.rpcPayProductService.selectAll(payProduct);
            for (PayProduct p:payProductlist) {
                object.put( "productName",p.getProductName());
                object.put( "payProductId",p.getId());
            }
            objects.add(object);
        }
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(objects, count));
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @MethodLog( remark = "删除渠道商对应通道" )
    public ResponseEntity<?> delete(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String channelIds = getStringRequired(param, "ids");
        String[] ids = channelIds.split(",");
        List<Long> rids = new LinkedList<>();
        for(String id : ids) {
            if(NumberUtils.isDigits(id)) rids.add(Long.parseLong(id));
        }
        rpcCommonService.rpcChannelMchChannelInfoService.batchDeleteChannelMch(rids);
        return ResponseEntity.ok(BizResponse.buildSuccess());
    }

    @RequestMapping("/updateStatus")
    @ResponseBody
    @MethodLog( remark = "修改渠道商通道状态" )
    public ResponseEntity<?> updateStatus(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        String status = getStringRequired(param, "status");
        ChannelMchChannelInfo channelMchChannelInfo = new ChannelMchChannelInfo();
        Byte channelStatus;
        if(status.equals("true")){
            channelStatus=1;
        }else {
            channelStatus=0;
        }
        channelMchChannelInfo.setId(id);
        channelMchChannelInfo.setStatus(channelStatus);
        rpcCommonService.rpcChannelMchChannelInfoService.update(channelMchChannelInfo);
        return ResponseEntity.ok(BizResponse.buildSuccess());
    }


//    @RequestMapping("/update")
//    @ResponseBody
//    @MethodLog( remark = "配置代理商支付通道" )
//    public ResponseEntity<?> update(HttpServletRequest request) {
//        JSONObject param = getJsonParam(request);
//        AgentPassage agentPassage = getObject(param, AgentPassage.class);
//        Long parentAgentId = rpcCommonService.rpcAgentInfoService.findByAgentId(agentPassage.getAgentId()).getParentAgentId();
//        if (parentAgentId != null && parentAgentId!=0){
//            AgentPassage ap = rpcCommonService.rpcAgentPassageService.findByAgentIdAndProductId(parentAgentId,agentPassage.getProductId());
//            BigDecimal parentAgentRate = null;
//            if (ap != null){
//                parentAgentRate = ap.getAgentRate();
//            }
//            if (parentAgentRate == null) return ResponseEntity.ok(BizResponse.build(RetEnum.RET_PARENTAGENTRATE_NOT_EXIST));
//            if (parentAgentRate.compareTo(agentPassage.getAgentRate()) == 1){
//                return ResponseEntity.ok(BizResponse.build(RetEnum.RET_AGENT_AGENTRATE_SET_MIRROR));
//            }
//        }
//        int count;
//        if(agentPassage.getId() != null) {
//            count = rpcCommonService.rpcAgentPassageService.update(agentPassage);
//        }else {
//            count = rpcCommonService.rpcAgentPassageService.add(agentPassage);
//        }
//        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
//        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
//    }

}
